<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户健康指标管理</title>
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body>
    <header>
        <h1>个人健康管理系统</h1>
        <nav>
            <ul>
                <li><a th:href="@{/}">首页</a></li>
                <li><a th:href="@{/foods}">食物管理</a></li>
                <li><a th:href="@{/users}">用户管理</a></li>
                <li><a th:href="@{/dietplans}">膳食计划</a></li>
                <li><a th:href="@{/userhealthindices}" class="active">健康指标</a></li>
            </ul>
        </nav>
    </header>

    <main class="container">
        <h2>用户健康指标管理</h2>

        <!-- 添加用户健康指标表单 -->
        <h3>添加新健康指标</h3>
        <form id="addUserHealthIndexForm" action="/api/userhealthindices" method="post">
            <div class="form-group">
                <label for="addUserId">用户ID:</label>
                <input type="number" id="addUserId" name="userId" required>
            </div>
            <div class="form-group">
                <label for="addRecordDate">记录日期:</label>
                <input type="date" id="addRecordDate" name="recordDate" required>
            </div>
            <div class="form-group">
                <label for="addWeight">体重(kg):</label>
                <input type="number" id="addWeight" name="weight" step="0.01" required>
            </div>
            <div class="form-group">
                <label for="addHeight">身高(cm):</label>
                <input type="number" id="addHeight" name="height" step="0.01" required>
            </div>
            <div class="form-group">
                <label for="addBmi">BMI:</label>
                <input type="number" id="addBmi" name="bmi" step="0.01" required>
            </div>
            <div class="form-group">
                <label for="addBodyFat">体脂率(%):</label>
                <input type="number" id="addBodyFat" name="bodyFat" step="0.01">
            </div>
            <div class="form-group">
                <label for="addHeartRate">心率(BPM):</label>
                <input type="number" id="addHeartRate" name="heartRate">
            </div>
            <div class="form-group">
                <label for="addBloodPressureSystolic">收缩压:</label>
                <input type="number" id="addBloodPressureSystolic" name="bloodPressureSystolic">
            </div>
            <div class="form-group">
                <label for="addBloodPressureDiastolic">舒张压:</label>
                <input type="number" id="addBloodPressureDiastolic" name="bloodPressureDiastolic">
            </div>
            <button type="submit" class="btn">添加健康指标</button>
        </form>

        <!-- 用户健康指标列表 -->
        <h3>所有用户健康指标</h3>
        <table id="userHealthIndexTable">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>用户ID</th>
                    <th>记录日期</th>
                    <th>体重(kg)</th>
                    <th>身高(cm)</th>
                    <th>BMI</th>
                    <th>体脂率(%)</th>
                    <th>心率(BPM)</th>
                    <th>收缩压</th>
                    <th>舒张压</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- 用户健康指标数据将通过JavaScript加载 -->
            </tbody>
        </table>

        <!-- 编辑用户健康指标表单 (初始隐藏) -->
        <h3 id="editFormTitle" style="display: none;">编辑健康指标</h3>
        <form id="editUserHealthIndexForm" style="display: none;" action="" method="put">
            <input type="hidden" id="editId" name="id">
            <div class="form-group">
                <label for="editUserId">用户ID:</label>
                <input type="number" id="editUserId" name="userId" required>
            </div>
            <div class="form-group">
                <label for="editRecordDate">记录日期:</label>
                <input type="date" id="editRecordDate" name="recordDate" required>
            </div>
            <div class="form-group">
                <label for="editWeight">体重(kg):</label>
                <input type="number" id="editWeight" name="weight" step="0.01" required>
            </div>
            <div class="form-group">
                <label for="editHeight">身高(cm):</label>
                <input type="number" id="editHeight" name="height" step="0.01" required>
            </div>
            <div class="form-group">
                <label for="editBmi">BMI:</label>
                <input type="number" id="editBmi" name="bmi" step="0.01" required>
            </div>
            <div class="form-group">
                <label for="editBodyFat">体脂率(%):</label>
                <input type="number" id="editBodyFat" name="bodyFat" step="0.01">
            </div>
            <div class="form-group">
                <label for="editHeartRate">心率(BPM):</label>
                <input type="number" id="editHeartRate" name="heartRate">
            </div>
            <div class="form-group">
                <label for="editBloodPressureSystolic">收缩压:</label>
                <input type="number" id="editBloodPressureSystolic" name="bloodPressureSystolic">
            </div>
            <div class="form-group">
                <label for="editBloodPressureDiastolic">舒张压:</label>
                <input type="number" id="editBloodPressureDiastolic" name="bloodPressureDiastolic">
            </div>
            <button type="submit" class="btn">保存更改</button>
            <button type="button" class="btn btn-danger" onclick="hideEditForm()">取消</button>
        </form>

    </main>

    <footer>
        <p>&copy; 2025 个人健康管理系统</p>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            fetchUserHealthIndices();

            // 处理添加用户健康指标表单提交
            document.getElementById('addUserHealthIndexForm').addEventListener('submit', function(event) {
                event.preventDefault();
                const formData = new FormData(event.target);
                const healthIndexData = Object.fromEntries(formData.entries());

                // 将userId转换为User对象
                healthIndexData.user = { id: parseInt(healthIndexData.userId) };
                delete healthIndexData.userId;

                healthIndexData.bodyFat = healthIndexData.bodyFat;
                delete healthIndexData.bodyFat;

                fetch('/api/userhealthindices', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(healthIndexData)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不佳');
                    }
                    return response.json();
                })
                .then(() => {
                    fetchUserHealthIndices(); // 刷新列表
                    event.target.reset(); // 重置表单
                })
                .catch(error => console.error('添加用户健康指标失败:', error));
            });

            // 处理编辑用户健康指标表单提交
            document.getElementById('editUserHealthIndexForm').addEventListener('submit', function(event) {
                event.preventDefault();
                const healthIndexId = document.getElementById('editId').value;
                const formData = new FormData(event.target);
                const healthIndexData = Object.fromEntries(formData.entries());

                // 将userId转换为User对象
                healthIndexData.user = { id: parseInt(healthIndexData.userId) };
                delete healthIndexData.userId;

                healthIndexData.bodyFat = healthIndexData.bodyFat;
                delete healthIndexData.bodyFat;

                fetch(`/api/userhealthindices/${healthIndexId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(healthIndexData)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不佳');
                    }
                    return response.json();
                })
                .then(() => {
                    fetchUserHealthIndices(); // 刷新列表
                    hideEditForm(); // 隐藏编辑表单
                })
                .catch(error => console.error('更新用户健康指标失败:', error));
            });
        });

        function fetchUserHealthIndices() {
            fetch('/api/userhealthindices')
                .then(response => response.json())
                .then(userHealthIndices => {
                    const tbody = document.querySelector('#userHealthIndexTable tbody');
                    tbody.innerHTML = ''; // 清空现有内容
                    userHealthIndices.forEach(index => {
                        const row = tbody.insertRow();
                        row.innerHTML = `
                            <td>${index.id}</td>
                            <td>${index.user ? index.user.id : 'N/A'}</td>
                            <td>${index.recordDate ? new Date(index.recordDate).toLocaleDateString() : 'N/A'}</td>
                            <td>${index.weight}</td>
                            <td>${index.height}</td>
                            <td>${index.bmi}</td>
                            <td>${index.bodyFat || ''}</td>
                            <td>${index.heartRate || ''}</td>
                            <td>${index.bloodPressureSystolic || ''}</td>
                            <td>${index.bloodPressureDiastolic || ''}</td>
                            <td>
                                <button class="btn" onclick="editUserHealthIndex(${index.id})">编辑</button>
                                <button class="btn btn-danger" onclick="deleteUserHealthIndex(${index.id})">删除</button>
                            </td>
                        `;
                    });
                })
                .catch(error => console.error('获取用户健康指标列表失败:', error));
        }

        function editUserHealthIndex(id) {
            fetch(`/api/userhealthindices/${id}`)
                .then(response => response.json())
                .then(index => {
                    document.getElementById('editId').value = index.id;
                    document.getElementById('editUserId').value = index.user ? index.user.id : '';
                    // 对于日期字段，需要特殊处理以确保格式正确
                    const recordDate = index.recordDate ? new Date(index.recordDate) : null;
                    if (recordDate) {
                        document.getElementById('editRecordDate').value = recordDate.toISOString().split('T')[0];
                    }
                    document.getElementById('editWeight').value = index.weight;
                    document.getElementById('editHeight').value = index.height;
                    document.getElementById('editBmi').value = index.bmi;
                    document.getElementById('editBodyFat').value = index.bodyFat || '';
                    document.getElementById('editHeartRate').value = index.heartRate || '';
                    document.getElementById('editBloodPressureSystolic').value = index.bloodPressureSystolic || '';
                    document.getElementById('editBloodPressureDiastolic').value = index.bloodPressureDiastolic || '';
                    
                    document.getElementById('editFormTitle').style.display = 'block';
                    document.getElementById('editUserHealthIndexForm').style.display = 'block';
                })
                .catch(error => console.error('获取用户健康指标详情失败:', error));
        }

        function hideEditForm() {
            document.getElementById('editFormTitle').style.display = 'none';
            document.getElementById('editUserHealthIndexForm').style.display = 'none';
            document.getElementById('editUserHealthIndexForm').reset();
        }

        function deleteUserHealthIndex(id) {
            if (confirm('确定要删除此健康指标吗？')) {
                fetch(`/api/userhealthindices/${id}`, {
                    method: 'DELETE'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不佳');
                    }
                    fetchUserHealthIndices(); // 刷新列表
                })
                .catch(error => console.error('删除健康指标失败:', error));
            }
        }
    </script>
</body>
</html> 